package com.XSQS.storage.index;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;


public class InvertedWordItem implements Comparable<InvertedWordItem>{
	private String key;
	private int firstEntry;
	private int lastEntry;
	
	public static final int ENTRY_POINTER_LENGTH=4;
	
	public InvertedWordItem(){
		
	}
	
	public InvertedWordItem(byte[] data) throws IOException{
		build(data);
	}
	
	public InvertedWordItem(String key, int firstEntry,int lastEntry){
		this.key=key;
		this.firstEntry=firstEntry;
		this.lastEntry=lastEntry;
	}
	
	public void build(byte[] data) throws IOException{
		if(data.length<=ENTRY_POINTER_LENGTH*2){
			char[] buf=new char[data.length];
			for(int i=0;i<data.length;++i){
				buf[i]=(char) data[i];
			}
			String str=String.valueOf(buf);
			IOException e=new IOException("The data is not complete."+str);
			throw e;
		}
		DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
		int keyLen=data.length-ENTRY_POINTER_LENGTH*2;
		char[] buf=new char[keyLen];
		for(int i=0;i<keyLen;++i){
			buf[i]=(char) dis.readByte();
		}
		key=String.valueOf(buf);
		firstEntry=dis.readInt();
		lastEntry=dis.readInt();
	}
	
	public byte[] toByteArray() throws IOException{
		int size=key.length()+ENTRY_POINTER_LENGTH*2;
		ByteArrayOutputStream baos = new ByteArrayOutputStream(size);
		DataOutputStream dos = new DataOutputStream(baos);
		dos.write(key.getBytes());
		dos.writeInt(firstEntry);
		dos.writeInt(lastEntry);
		return baos.toByteArray();
	}
	
	public void setKey(String key) {
		this.key = key;
	}
	public String getKey() {
		return key;
	}
	public void setFirstEntry(int firstEntry) {
		this.firstEntry = firstEntry;
	}
	public int getFirstEntry() {
		return firstEntry;
	}
	public void setLastEntry(int lastEntry) {
		this.lastEntry = lastEntry;
	}
	public int getLastEntry() {
		return lastEntry;
	}

//	@Override
	public int compareTo(InvertedWordItem other) {
		if(other==null){
			return -1; 
		}
		if(other==this){
			return 1;
		}
		return this.key.compareTo(other.key);
	}
	
	@Override
	public String toString(){
        StringBuffer sb = new StringBuffer();
        sb.append(key + " | ");
        sb.append(firstEntry + " | ");
        sb.append(lastEntry + " | ");
        return sb.toString();
    }
	
}
